package org.amicofragile.bank;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Bank {
	private Scanner scanner;
	
	private Map<Long, Account> accounts;
	
	private DataAccessObject dao;
	
	private PromotionManager promotionManager;
	
	public Bank(DataAccessObject dao, PromotionManager pm) {
		this.dao = dao;
		this.promotionManager = pm;
		this.accounts = new HashMap<Long, Account>();
		scanner = new Scanner(System.in);
		scanner.useDelimiter(System.getProperty("line.separator"));
	}
	
	public Account createNewAccount(Person owner) {
		Account account = new Account(new Long(accounts.size() + 1), owner);
		accounts.put(account.getId(), account);
		this.dao.save(account);
		return account;
	}

	public void run() {
		System.out.println("Welcome to bank!");
		boolean running = true;
		while(running) {
			running = mainMenu();
		}
		System.out.println("Bye bye!");
	}

	private boolean mainMenu() {
		System.out.println("** Main menu **");
		System.out.println("0) Exit");
		System.out.println("1) Create new account");
		System.out.print("==> ");
		int choice = Integer.parseInt(scanner.nextLine());
		switch (choice) {
		case 1:
			createNewAccount();
			break;
		}
		return choice != 0;
	}

	private void createNewAccount() {
		System.out.println("Account creation wizard");
		System.out.print("Account owner: first name ");
		String firstName = scanner.nextLine();
		System.out.print("Account owner: last name ");
		String lastName = scanner.nextLine();
		Person owner = new Person(firstName, lastName);
		Account a = createNewAccount(owner);
		System.out.printf("Created account %d for owner %s %s\n", a.getId(), owner.getFirstname(), owner.getSurname());
		this.promotionManager.applyPromotions(a);
		System.out.printf("Applied promotions: account value is %f\n", a.getAmount());
	}
}
